package com.itheima.service.impl;

import com.itheima.entity.Dept;
import com.itheima.entity.DeptLog;
import com.itheima.entity.Result;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    DeptMapper deptMapper;

    @Autowired
    EmpMapper empMapper;

    @Autowired
    DeptLogService deptLogService;

    // 查询所有部门列表业务功能实现
    @Override
    public List<Dept> ListDept() {
        // 1.调用持久层mapper，查询数据表dept中的所有部门列表数据
        List<Dept> deptList = deptMapper.selectAll();

        //模拟异常
        //int num = 10/0;

        // 2.返回查询结果
        return deptList;
    }


    //根据id删除部门信息
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void removeById(Integer id) throws ClassNotFoundException {
        try {
            //1. 调用持久层mapper， 删除数据表dept中指定的部门信息
            deptMapper.deleteBuId(id);
            //开除当前部门中的所有员工：delete from emp wherre dept_id = ?
            // 模拟异常
            if (true){
                throw new ClassNotFoundException();
            }
            empMapper.deleteBydeptId(id);
        } finally {
            //不论是否有异常，最终都要执行的代码：记录日志
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门的操作，此时解散的是"+id+"号部门");
            //调用其他业务类中的方法
            deptLogService.insert(deptLog);
        }
    }

    // 添加部门业务方法
    @Override
    public void saveDept(Dept dept) {
        // 1. 补全基础属性：createTime  / updateTime
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        // 2.调用持久层mapper， 向数据表dept中添加新的的部门信息
        deptMapper.insert(dept);
    }
   /* // 根据id
    @Override
    public void listDept(Integer id) {
        deptMapper.listDept(id);
    }*/
    //修改
    @Override
    public void update(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        deptMapper.update(dept);
    }

    @Override
    public Dept selectbd(Integer id) {
        return deptMapper.selectb(id);

    }
}
